import 'dart:convert';
import 'dart:io';

import 'package:bloc/bloc.dart';
import 'package:flutter/cupertino.dart';
import 'package:joyagoo/pages/widget/joy_loading_widget.dart';

import '../model/categoryModel.dart';
import '../model/productListModel.dart';
import '../request/LoadingUtil.dart';
import '../request/api_manager.dart';
import '../utils/category_manager.dart';

part 'joy_home_event.dart';
part 'joy_home_state.dart';

class JoyHomeBloc extends Bloc<JoyHomeEvent, JoyHomeState> {
  JoyHomeBloc() : super(JoyHomeInitial()) {
    on<JoyHomeEvent>((event, emit) {
      // TODO: implement event handler
    });


    on<GetJOYSearchCategoryProductEvent>((event, emit) async {
      // TODO: implement event handler
      Map<String, dynamic> params = {};
      params["pageNo"] = event.pageNum;
      params["pageSize"] = event.pageSize;
      // 🔥 处理分类名称，去除多余空格
      String processedCategory = event.category.trim();
      debugPrint("🔥 原始分类: '${event.category}'");
      debugPrint("🔥 处理后分类: '$processedCategory'");
      params["category"] = processedCategory;
      params["sortColumn"] = event.sortColumn;
      params["orderBy"] = event.orderBy;

      if(event.pageNum ==1){
        JoyLoadingWidget.show(event.context);
      }
      await ApiManager.getCategoryProduct(
        params,
        success: (result) {
          JoyLoadingWidget.hide();
          ProductListModel modelList = ProductListModel.fromJson(result);
          emit(GetJOYSearchCategoryProductEventSuccess(modelList));
        },
        fail: (message) {
          debugPrint("message 1=1 $message");

          JoyLoadingWidget.hide();
          emit(GetJOYSearchCategoryProductEventFailure(message));
        },
      );
    });

    // 添加搜索产品事件处理器
    on<GetJOYSearchProductEvent>((event, emit) async {
      Map<String, dynamic> params = {};
      params["pageNo"] = event.pageNum;
      params["pageSize"] = event.pageSize;
      // 🔥 将空格替换为下划线或其他字符，避免URL编码问题
      // 如果后端期望使用其他分隔符，可以修改这里
      String processedProductName = event.productName.trim();
      debugPrint("🔥 原始搜索词: '${event.productName}'");
      debugPrint("🔥 处理后搜索词: '$processedProductName'");

      params["productName"] = processedProductName;

      // params["category"] = processedProductName; // 使用 category 参数进行搜索

      if(event.pageNum == 1){
        JoyLoadingWidget.show(event.context);
      }
      await ApiManager.getCategoryProduct(
        params,
        success: (result) {
          JoyLoadingWidget.hide();
          ProductListModel modelList = ProductListModel.fromJson(result);
          emit(GetJOYSearchProductEventSuccess(modelList));
        },
        fail: (message) {
          debugPrint("GetJOYSearchProductEvent error: $message");
          JoyLoadingWidget.hide();
          emit(GetJOYSearchProductEventFailure(message));
        },
      );
    });

    on<GetJOYHomeDataBannerAndProductEvent>((event, emit) async {
      // TODO: implement event handler
      Map<String, dynamic> params = {};
      params["websiteName"] = event.websiteName;
      JoyLoadingWidget.show(event.context);
      await ApiManager.getHomeBannerAndProduct(
        params,
        success: (result) {
          JoyLoadingWidget.hide();
          emit(GetJOYHomeDataBannerAndProductEventSuccess(result));
        },
        fail: (message) {
          debugPrint("message 1=1 $message");

          JoyLoadingWidget.hide();
          emit(GetJOYHomeDataBannerAndProductEventFailure(message));
        },
      );
    });

    on<GetJOYHomeCategoryEvent>((event, emit) async {
      // TODO: implement event handler
      Map<String, dynamic> params = {};
      params["platform"] = event.platform;
      if(event.CategoryID != ""){
        params["categoryId"] = event.CategoryID;

      }

      JoyLoadingWidget.show(event.context);
      await ApiManager.getHomeCategory(
        params,
        success: (result) {
          JoyLoadingWidget.hide();
          List<CategoryModel> resultList = categoryModelFromJson(json.encode(result));
          debugPrint("GetJOYHomeCategoryEvent $resultList");

           if(event.CategoryID != ""){
       

           } else {
          // 🔥 将分类数据存储到全局管理器中
             try {
              final categoryManager = CategoryManager.instance;
              categoryManager.setCategories(resultList);
              debugPrint("CategoryManager: 已保存 ${resultList.length} 个分类到全局管理器");
              debugPrint("CategoryManager: 保存后状态 - hasCategories=${categoryManager.hasCategories}, 分类数量=${categoryManager.categories.length}");
             } catch (e) {
              debugPrint("CategoryManager: 保存分类数据时出错: $e");
              debugPrint("CategoryManager: 错误详情 - ${e.toString()}");
            }
          }

          emit(GetJOYHomeCategoryEventSuccess(result));
        },
        fail: (message) {
          debugPrint("message 1=1 $message");

          JoyLoadingWidget.hide();
          emit(GetJOYHomeCategoryEventFailure(message));
        },
      );
    });

    on<PostJOYUserLoginEvent>((event, emit) async {
      // TODO: implement event handler
      Map<String, dynamic> params = {};
      params["username"] = event.userName;
      params["password"] = event.pwd;

      JoyLoadingWidget.show(event.context);
      await ApiManager.postLoginUser(
        params,
        success: (result) {
          JoyLoadingWidget.hide();
          emit(postUserLoginEventSuccess(result));
        },
        fail: (message) {
          debugPrint("message 1=1 $message");

          JoyLoadingWidget.hide();
          emit(postUserLoginEventFailure(message));
        },
      );
    });

    on<PostJOYUserLoginOutEvent>((event, emit) async {
      // TODO: implement event handler
      Map<String, dynamic> params = {};
      params["username"] = event.userName;
      params["password"] = event.pwd;
      params["type"] = event.type;

      JoyLoadingWidget.show(event.context);
      await ApiManager.postLoginOutUser(
        params,
        success: (result) {
          JoyLoadingWidget.hide();
          emit(postUserLoginOutEventSuccess(event.type));
        },
        fail: (message) {
          debugPrint("message 1=1 $message");

          JoyLoadingWidget.hide();
          emit(postUserLoginOutEventFailure(message));
        },
      );
    });

    on<GetJOYProductDetailEvent>((event, emit) async {
      // TODO: implement event handler
      Map<String, dynamic> params = {};
      params["itemNo"] = event.itemNo;
      params["channel"] = event.channel;
      // params["platformName"] = event.platformName;

      JoyLoadingWidget.show(event.context);
      await ApiManager.getProductDetail(
        params,
        success: (result) {
          JoyLoadingWidget.hide();
          emit(GetJOYProductDetailEventSuccess(result));
        },
        fail: (message) {
          debugPrint("message 1=1 $message");

          JoyLoadingWidget.hide();
          emit(GetJOYProductDetailEventFailure(message));
        },
      );
    });

    on<GetJOYSearchKeyListEvent>((event, emit) async {
      // TODO: implement event handler
      Map<String, dynamic> params = {};
      params["productName"] = event.productName;

      await ApiManager.getsearchKey(
        params,
        success: (result) {
          LoadingUtil.close();
          emit(GetJOYSearchKeyListEventSuccess(result));
        },
        fail: (message) {
          debugPrint("message 1=1 $message");

          LoadingUtil.close();
          emit(GetJOYSearchKeyListEventFailure(message));
        },
      );
    });


    on<GetJOYHotProductListEvent>((event, emit) async {
      // TODO: implement event handler
      Map<String, dynamic> params = {};
      params["pageNo"] = event.pageNum;
      params["pageSize"] = event.pageSize;
      if(event.needLoad == true){
        JoyLoadingWidget.show(event.context);
      }

      await ApiManager.getHotProductList(
        params,
        success: (result) {
          JoyLoadingWidget.hide();
          emit(GetJOYHotProductListEventSuccess(result));
        },
        fail: (message) {
          debugPrint("message 1=1 $message");

          JoyLoadingWidget.hide();
          emit(GetJOYHotProductListEventFailure(message));
        },
      );
    });

    // 上传文件（优化版）
    on<PostUploadFileEvent>((event, emit) async {

      // LoadingUtil.show(event.context);
      JoyLoadingWidget.show(
        event.context,
        text: 'Uploading file...',
      );

      try {
        // 基础文件验证
        if (event.imageFile.isEmpty) {
          LoadingUtil.close();
          emit(PostUploadFileEventFailure('File path cannot be empty'));
          return;
        }

        // 检查文件是否存在
        final file = File(event.imageFile);
        if (!await file.exists()) {
          JoyLoadingWidget.hide();

          emit(PostUploadFileEventFailure('File does not exist' + ': ${event.imageFile}'));
          return;
        }

        // 检查文件大小（限制为10MB）
        final fileSizeInBytes = await file.length();
        final fileSizeInMB = fileSizeInBytes / (1024 * 1024);
        if (fileSizeInMB > 10.0) {
          JoyLoadingWidget.hide();
          emit(PostUploadFileEventFailure('File is too large' + ': ${fileSizeInMB.toStringAsFixed(2)}MB, maximum allowed: 10MB'));
          return;
        }

        // 检查文件类型
        final allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
        final fileExtension = event.imageFile.toLowerCase().substring(event.imageFile.lastIndexOf('.'));
        if (!allowedExtensions.contains(fileExtension)) {
          emit(PostUploadFileEventFailure('Unsupported file type' + ': $fileExtension'));
          return;
        }

        // 构建上传参数
        Map<String, dynamic> params = {
          'image': event.imageFile, // 将图片文件路径添加到FormData中
          'uploadTime': DateTime.now().millisecondsSinceEpoch.toString(), // 添加上传时间戳
        };

        // 执行上传
        await ApiManager.postUploadFile(
          params,
          success: (result) {
            debugPrint('File upload successful' + ': $result');
            emit(PostUploadFileEventSuccess(result));
          },
          fail: (message) {
            debugPrint('File upload failed' + ': $message');
            JoyLoadingWidget.hide();
            emit(PostUploadFileEventFailure(message));
          },
        );
      } catch (e) {
        debugPrint('Error occurred during upload' + ': $e');
        LoadingUtil.close();
        emit(PostUploadFileEventFailure('Error occurred during upload' + ': ${e.toString()}'));
      }
    });


    // 找相似 图片搜索
    on<GetSearchSimilarityImageEvent>((event, emit) async {
      // 🔥 详细日志：请求开始
      debugPrint("=== GetSearchSimilarityImageEvent 请求开始 ===");
      debugPrint("图片文件: ${event.imageFile}");
      debugPrint("请求时间: ${DateTime.now()}");
      
      Map<String, dynamic> params = {};
      params["image"] = event.imageFile;
      
      debugPrint("请求参数: $params");
      
      await ApiManager.getSearchSimilarityImage(
        params,
        success: (result) {
          // 🔥 详细日志：请求成功
          debugPrint("=== GetSearchSimilarityImageEvent 请求成功 ===");
          debugPrint("原始响应数据: $result");
          debugPrint("响应数据类型: ${result.runtimeType}");
          debugPrint("响应数据是否为null: ${result == null}");

          LoadingUtil.close();

          if(result == null){
            debugPrint("⚠️ 警告：API返回数据为null，发送空的ProductListModel");
            // 🔥 发送空的ProductListModel，包含所有必需参数
            emit(GetSearchSimilarityImageEventSuccess(ProductListModel(
              productModels: [],
              total: 0,
              size: 0,
              current: 0,
              pages: 0,
            )));
            
          }else{
            try {
              ProductListModel modelList;
              
              // 🔥 判断返回数据类型
              if (result is List) {
                debugPrint("=== 数据类型：List ===");
                debugPrint("列表长度: ${result.length}");
                
                // 将List转换为ProductListModel格式
                List<ProductModel> products = [];
                for (var item in result) {
                  if (item is Map<String, dynamic>) {
                    products.add(ProductModel.fromJson(item));
                  }
                }
                
                // 🔥 构造ProductListModel对象，包含所有必需参数
                modelList = ProductListModel(
                  productModels: products,
                  total: products.length,
                  size: products.length,
                  current: 1,
                  pages: 1,
                );
                
              } else if (result is Map<String, dynamic>) {
                debugPrint("=== 数据类型：Map ===");
                modelList = ProductListModel.fromJson(result);
                
              } else {
                debugPrint("❌ 未知的数据类型: ${result.runtimeType}");
                emit(GetSearchSimilarityImageEventFailure("未知的数据格式"));
                return;
              }
              
              // 🔥 详细日志：数据解析成功
              debugPrint("=== 数据解析成功 ===");
              debugPrint("解析后的商品数量: ${modelList.productModels.length}");
              debugPrint("解析后的商品列表: ${modelList.productModels}");
              
              // 🔥 详细日志：商品详情
              if(modelList.productModels.isNotEmpty) {
                debugPrint("=== 相似商品详情 ===");
                for(int i = 0; i < modelList.productModels.length && i < 3; i++) {
                  var product = modelList.productModels[i];
                  debugPrint("相似商品${i+1}: ${product.title} - ${product.price}");
                }
                if(modelList.productModels.length > 3) {
                  debugPrint("... 还有${modelList.productModels.length - 3}个相似商品");
                }
              } else {
                debugPrint("⚠️ 警告：解析后的商品列表为空！");
              }
              
              emit(GetSearchSimilarityImageEventSuccess(modelList));
              debugPrint("✅ 成功发送GetSearchSimilarityImageEventSuccess事件");
              
            } catch (e, stackTrace) {
              debugPrint("❌ 数据解析失败: $e");
              debugPrint("错误堆栈: $stackTrace");
              debugPrint("原始数据: $result");
              debugPrint("原始数据类型: ${result.runtimeType}");
              emit(GetSearchSimilarityImageEventFailure("数据解析失败: $e"));
            }
          }
        },
        fail: (message) {
          // 🔥 详细日志：请求失败
          debugPrint("=== GetSearchSimilarityImageEvent 请求失败 ===");
          debugPrint("失败信息: $message");
          debugPrint("失败信息类型: ${message.runtimeType}");
          debugPrint("失败时间: ${DateTime.now()}");

          LoadingUtil.close();

          emit(GetSearchSimilarityImageEventFailure(message));
          debugPrint("❌ 发送GetSearchSimilarityImageEventFailure事件");
        },
      );
    });


    // 判断当前产品是否收藏
    on<postProductIsCollectedEvent>((event, emit) async {
      Map<String, dynamic> params = {};
      params["spu"] =event.spu;
      await ApiManager.getProductIsCollected(
        params,
        success: (result) {
          emit(postProductIsCollectedEventSuccess(result));
        },
        fail: (message) {
          emit(postProductIsCollectedEventFailure(message));
        },
      );
    });


    // 添加收藏
    on<postAddProductCollectedEvent>((event, emit) async {
      Map<String, dynamic> params = {};
      params["spu"] =event.spu;

      await ApiManager.postAddProductCollected(
        params,
        success: (result) {
          emit(postAddProductCollectedEventSuccess(result));
        },
        fail: (message) {
          emit(postAddProductCollectedEventFailure(message));
        },
      );
    });

    // 收藏列表
    on<PostProductCollectedListEvent>((event, emit) async {
      Map<String, dynamic> params = {};
      params["pageSize"] =event.pageSize;
      params["pageNo"] =event.pageNum;
      await ApiManager.getProductCollectedList(
        params,
        success: (result) {
          ProductListModel modelList = ProductListModel.fromJson(result);

          emit(PostProductCollectedListEventSuccess(modelList));
        },
        fail: (message) {

          emit(PostProductCollectedListEventFailure(message));
        },
      );
    });

    on<GetSearchImageEvent>((event, emit) async {
      Map<String, dynamic> params = {};
      params["channel"] =event.channel;
      params["pageNo"] =event.pageNum;
      params["pageSize"] =event.pageSize;
      params["imageUrl"] =event.imageFile;

      if (event.sort != -1) {
        Map asc = {"price":"asc"};
        Map desc = {"rePurchaseRate":"desc"};
        params['sort'] = (event.sort == 1)?asc:desc;
      }

      if(event.pageNum == 1){
        JoyLoadingWidget.show(event.context,text: "Loading...");

      }
      await ApiManager.getSearchImage(
        params,
        success: (result) {
          JoyLoadingWidget.hide();


          if(result == null){
            emit(GetSearchImageEventSuccess([]));
          }else{
            ProductListModel modelList = ProductListModel.fromJson(result);
            emit(GetSearchImageEventSuccess(modelList));

          }

        },
        fail: (message) {
          JoyLoadingWidget.hide();
          emit(GetSearchImageEventFailure(message));
        },
      );
    });


    on<GetSearchNewImageEvent>((event, emit) async {
      Map<String, dynamic> params = {};
      params["image"] =event.imageFile;
      // params["pageNo"] =1;
      // params["pageSize"] =10;


      JoyLoadingWidget.show(event.context,text: "Loading...");


      await ApiManager.getSearchImage(
        params,
        success: (result) {
          JoyLoadingWidget.hide();


          if(result == null){
            emit(GetSearchImageEventSuccess([]));
          }else{
            ProductListModel modelList = ProductListModel.fromJson(result);
            emit(GetSearchImageEventSuccess(modelList));

          }

        },
        fail: (message) {
          JoyLoadingWidget.hide();
          emit(GetSearchImageEventFailure(message));
        },
      );
    });

    //
    on<GetHistoryProductViewEvent>((event, emit) async {

      Map<String, dynamic> params = {};
      params["pageNo"] =event.pageNum;
      params["pageSize"] =event.pageSize;
      if(event.pageNum == 1){
        JoyLoadingWidget.show(event.context,text: "Loading...");
      }
      await ApiManager.getUserBrowseProduct(
        params,
        success: (result) {
          JoyLoadingWidget.hide();

          ProductListModel modelList = ProductListModel.fromJson(result);
          emit(GetHistoryProductViewEventSuccess(modelList));
        },
        fail: (message) {
          JoyLoadingWidget.hide();
          emit(GetHistoryProductViewEventFailure(message));
        },
      );
    });

  }





}
